const app = getApp();
import { Product } from '../../pages/product/product-model.js';
var product = new Product(); 
import { Fenxiao } from '../../pages/fenxiao/fenxiao-model.js';
var fenxiao = new Fenxiao(); 
Component({
  properties: {
    user: { // 图片
      type: Object,
      value: ''
    },
    param:{
      type: Object,
      value: ''
    }
  },
  data: {
    showpost: false,
    imgHeight: 0,
    qrCode: "", //二维码
    diyImg:"https://mini.888dcy.com/storage/1.jpg", //个性图片
    diyImgInfo:{},
    qrCode:"https://mini.888dcy.com/storage/qrcode.jpg", //二维码
    userAvatar:'',
    showShareImg: false,
    bg:"",
  },

  ready: function() {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取随机的个性图片地址,在前端随机
    getDiy: function (hasPost){
      var config = wx.getStorageSync('config');
      this.data.site_name = config[2].value;
      var that = this;
      that.setData({
        showpost: true
      })
      if (hasPost) {
        return false;
      }
      wx.showLoading({
        title: '正在加载图片',
        mask: true,
      });
      var param = {'num': 20, 'key': 'shop' };
      fenxiao.getDiyImage(param, (res) => {
        if(res.items.length == 0){
          wx.showToast({
            title: '无法获取个性图片',
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            that.closePoste(false);
          }, 2000)
        }else{
          var random = that.getRandomNum(0, res.items.length-1);
          that.data.diyImg = res.items[random].image;
          that.setDiy();
        }
      }) 
    },
    //// 获取最小值到最大值之前的整数随机数
    getRandomNum:function (Min, Max) {
      var Range = Max - Min;
      var Rand = Math.random();
      return(Min + Math.round(Rand * Range));
    },
    //下载diy图片
    setDiy: function () {
      var that = this;
      var diyImg = that.data.diyImg;
      if (diyImg) {
        wx.downloadFile({
          url: diyImg,
          success: function(res) {
            if (res.statusCode === 200) {
              var imgSrc = res.tempFilePath;
              that.calculateImg(imgSrc, function(data) {
                that.setData({
                  diyImg: imgSrc,
                  diyImgInfo : data
                });
                that.getQrcode();
              })
            } else {
              wx.showToast({
                title: '个性图片下载失败！',
                icon: 'none',
                duration: 2000,
                success: function() {
                  that.getQrcode();
                }
              })
            }
          }
        })
      } else {
        that.getQrcode();
      }
    },
    //下载二维码
    getQrcode:function(){
      var that = this;
      var qrCode = '';
      /*自定义路径，如没有则默认为首页 */
      console.log(this.data.param);
      if(this.data.param){
        param = this.data.param;
      }else{
        var pid = that.data.user ? that.data.user.id : '';
        if(!pid){
          pid = wx.getStorageSync('uid');
        }
        var param = {
          page: 'pages/home/home',
          scene: 'pid=' + pid
        }
      }
      product.qrcode(param, (res) => {
        if (res.status != 1) {
          wx.showToast({
            title: '二维码生成失败，请稍后重试',
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            that.closePoste(false);
          }, 2000)
        } else {
          qrCode = res.data;
          wx.downloadFile({
            url: qrCode,
            success: function (res) {
              if (res.statusCode === 200) {
                var imgSrc = res.tempFilePath;
                that.setData({
                  qrCode: imgSrc
                });
                that.getAvatar();
              } else {
                wx.showToast({
                  title: '二维码下载失败！',
                  icon: 'none',
                  duration: 2000,
                  success: function () {
                    that.getAvatar();
                  }
                })
              }
            }
          })
        }
      })
    },
    //下载用户头像
    getAvatar:function(){
      var that = this;
      var avatarUrl = that.data.user ? that.data.user.avatarUrl : '';
      if (avatarUrl) {
        wx.downloadFile({
          url: avatarUrl,
          success: function (res) {
            if (res.statusCode === 200) {
              var imgSrc = res.tempFilePath;
              that.setData({
                userAvatar: imgSrc
              });
              that.sharePosteCanvas();
            } else {
              wx.showToast({
                title: '微信头像下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  that.sharePosteCanvas();
                }
              })
            }
          }
        })
      } else {
       
        that.sharePosteCanvas();
      }
    },
    //canvas绘制分享海报
    sharePosteCanvas: function () {
      wx.hideLoading();
      var imgInfo = this.data.diyImgInfo;
      wx.showLoading({
        title: '生成中...',
        mask: true,
      })
      var that = this;
      const ctx = wx.createCanvasContext('myCanvas', that);
      var width = "";
      const query = wx.createSelectorQuery().in(this);
      query.select('#canvas-container').boundingClientRect(function(rect) {
        if (imgInfo) {
          var imgheight = parseFloat(imgInfo);
        }
        var user = that.data.user;
        var height = rect.height;
        var right = rect.right;
        width = rect.width;
        var left = rect.left;
        //画布白色背景
        ctx.setFillStyle('#fff');
        ctx.fillRect(0, 0, width, height);
        //个性图片
        if (that.data.diyImg) {
          ctx.drawImage(that.data.diyImg, 0, 0, width, imgheight ? imgheight : width);
        }
        //  个人头像
        if (that.data.userAvatar) {
          ctx.drawImage(that.data.userAvatar, left -10 , imgheight + 30,40,40)
          ctx.setFontSize(12);
          ctx.setFillStyle('#000');
          var name = user.username ? user.username : user.nickName;
          if (name) {
            ctx.fillText(name, left + 45, imgheight + 55);
          }
        }
        //站点名称
        ctx.setFillStyle('#fec67d');
        ctx.fillText(that.data.site_name, left - 10, imgheight + 90);
        //二维码
        if (that.data.qrCode) {
          ctx.drawImage(that.data.qrCode, right - 140 , imgheight+10,90,90)
          ctx.setFontSize(12);
          ctx.setFillStyle('#000');
        }
      }).exec()
      setTimeout(function() {
        ctx.draw();
        wx.hideLoading();
        that.setData({
          showShareImg:true
        })
      }, 500)

    },

    textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
      let strLength = 0; // text byte length
      let rows = 1;
      let str = 0;
      let arr = [];
      for (let j = 0; j < text.length; j++) {
        if (text.charCodeAt(j) > 255) {
          strLength += 2;
          if (strLength > rows * num) {
            strLength++;
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        } else {
          strLength++;
          if (strLength > rows * num) {
            arr.push(text.slice(str, j));
            str = j;
            rows++;
          }
        }
      }
      arr.push(text.slice(str, text.length));
      return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
    },

    //点击保存到相册
    saveShareImg: function() {
      var that = this;
      wx.showLoading({
        title: '正在保存',
        mask: true,
      })
      setTimeout(function() {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: function(res) {
            wx.hideLoading();
            var tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showModal({
                  content: '图片已保存到相册，赶紧晒一下吧~',
                  showCancel: false,
                  confirmText: '好的',
                  confirmColor: '#333',
                  success: function(res) {
                    that.closePoste();
                    if (res.confirm) {
                    }
                  },
                  fail: function(res) {
                    console.log(res)
                  }
                })
              },
              fail: function(res) {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          },
          fail: function(err) {
            console.log(err)
          }
        }, that);
      }, 1000);
    },
    //关闭海报
    closePoste: function (status = true) {
      this.setData({
        showpost: false
      })
      this.triggerEvent('myevent', { 'status': status })
    },
    //计算图片尺寸
    calculateImg: function(src, cb) {
      var that = this;
      wx.getImageInfo({
        src: src,
        success(res) {
          wx.getSystemInfo({
            success(res2) {
              var ratio = res.width / res.height;
              var imgHeight = (res2.windowWidth * 0.85 / ratio) + 120; //画布的高度
              that.setData({
                imgHeight: imgHeight
              })
              cb(imgHeight - 120);  //返回图片的高度
            }
          })
        }
      })
    }
  }
})